package cn.com.b2office.struts2.action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import cn.com.b2office.domain.Item;
import cn.com.b2office.domain.ItemCollection;
import cn.com.b2office.domain.User;
import cn.com.b2office.service.CategoryService;
import cn.com.b2office.service.CollectionService;
import cn.com.b2office.service.ItemService;

import com.opensymphony.xwork2.ActionSupport;

public class ExportCollectionAction extends ActionSupport implements
		SessionAware {

	private static final long serialVersionUID = 2462794595113664086L;

	private Map session = null;

	private InputStream excelStream; // 需要生成getter和setter

	private String fileName = null;

	private CollectionService collectionService = null;

	private ItemService itemService = null;

	private CategoryService categoryService = null;

	public void setSession(Map session) {
		this.session = session;
	}

	public String execute() throws Exception {
		User user = (User) session.get("user");
		if (user == null)
			return "login";

		Date current = new Date();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

		fileName = df.format(current);

		StringBuffer excelBuf = new StringBuffer();

		excelBuf.append("商品编号").append("\t").append("商品名称").append("\t")
				.append("收藏日期").append("\n");

		List<ItemCollection> collections = collectionService.findAll(user
				.getMemberId());
		for (ItemCollection coll : collections) {
			Item item = itemService.getItem(coll.getItemId());
			if (item == null)
				continue;
			excelBuf.append(item.getItem_no()).append("\t").append(
					item.getTitles()).append("\t").append(
					df.format(coll.getModifytime())).append("\n");
		}

		String excelString = excelBuf.toString();
		excelStream = new ByteArrayInputStream(excelString.getBytes(), 0,
				excelString.length());
		return "excel";
	}

	public void setCollectionService(CollectionService collectionService) {
		this.collectionService = collectionService;
	}

	public void setItemService(ItemService itemService) {
		this.itemService = itemService;
	}

	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}

	public InputStream getExcelStream() {
		return excelStream;
	}

	public String getFileName() {
		return fileName;
	}

}
